<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>画板</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <link rel="stylesheet" type="text/css" href="./css/style.css"/>
</head>
<body>
<canvas id="canvas"></canvas>
<script type="text/javascript">
    let canvas = document.getElementById('canvas');
    /* 
     *  获取文档区域的宽和高度
     */
    canvas.width = document.documentElement.clientWidth;
    canvas.height = document.documentElement.clientHeight;


    let ctx = canvas.getContext('2d');
    let painting = false;
    let last;

    ctx.fillStyle = "rgb(200,0,0)"; // 填充颜色
    ctx.strokeStyle = 'none'; // 不描边，丝滑些
    ctx.lineWidth = 9;
    ctx.lineCap = "round"

    function drawLine(x1,y1,x2,y2){
        ctx.beginPath();
        ctx.moveTo(x1,y1);
        ctx.lineTo(x2,y2);
        ctx.stroke();
    }

    // 判断是否是触屏设备
    let isTouchDevice = 'ontouchstart' in document.documentElement;
    if (isTouchDevice) {

        canvas.ontouchstart = (e) => {
            let x = e.touches[0].clientX
            let y = e.touches[0].clientY
            last = [x,y]
        }
        canvas.ontouchmove = (e) => {
            e.preventDefault(); // 阻止移动端页面拖动
            let x = e.touches[0].clientX
            let y = e.touches[0].clientY
            drawLine(last[0], last[1], x, y)
            last = [x, y]
        }
    } else {
        canvas.onmousedown = (e) => {
            painting = true;
            last = [e.clientX,e.clientY]
        }
        canvas.onmousemove = (e) => {
            if (painting === true){
                drawLine(last[0], last[1], e.clientX, e.clientY)
                last = [e.clientX, e.clientY]
            }
        }
        canvas.onmouseup = () => {
            painting = false;
        }
    }
</script>
</body>
</html>